package com.web.cms.doc.util;

import com.blue.core.util.NumberUtil;
import com.blue.integration.serve.Bucket;
import com.blue.integration.serve.StorageClient;
import com.blue.jdbc.Page;
import com.web.cms.doc.message.DocFileRequest;
import com.web.cms.doc.message.DocFileResponse;
import com.web.cms.doc.model.DocFile;

import java.util.ArrayList;
import java.util.List;

public class DocFileConvertor
{
	private DocFileConvertor()
	{
	}
	
	public static DocFile toDocFile(DocFileRequest request)
	{
		if (request == null)
			return null;
		
		DocFile file = new DocFile();
		file.setId(request.getId());
		file.setDocId(request.getDocId());
		file.setWebId(request.getWebId());
		file.setName(request.getName());
		file.setKey(request.getKey());
		file.setSize(request.getSize());
		file.setPos(request.getPos());
		file.setUploadTime(request.getUploadTime());
		file.setType(request.getType());
		file.setMimeType(request.getMimeType());
		return file;
	}
	
	public static DocFileResponse toResponse(DocFile file, StorageClient storageClient)
	{
		if (file == null)
			return null;
		
		DocFileResponse response = new DocFileResponse();
		response.setId(file.getId());
		response.setDocId(file.getDocId());
		response.setWebId(file.getWebId());
		response.setName(file.getName());
		response.setKey(file.getKey());
		response.setSize(file.getSize());
		response.setUploadTime(file.getUploadTime());
		response.setType(file.getType());
		response.setPos(file.getPos());
		response.setMimeType(file.getMimeType());
		response.setDocTitle(file.getDocTitle());
		response.setWebName(file.getWebName());
		
		response.setSizeName(NumberUtil.byteFormat(response.getSize().longValue()));
		response.setUrl(storageClient.getUrl(Bucket.CMS, response.getKey()));
		return response;
	}
	
	public static List<DocFileResponse> toResponse(List<DocFile> list, StorageClient storageClient)
	{
		List<DocFileResponse> responseList = new ArrayList<>();
		if (list == null || list.isEmpty())
			return responseList;
		
		for (DocFile file : list)
		{
			responseList.add(toResponse(file, storageClient));
		}
		return responseList;
	}
	
	public static Page<DocFileResponse> toResponse(Page<DocFile> page, StorageClient storageClient)
	{
		Page<DocFileResponse> pageResponse = new Page<>();
		pageResponse.setCurPage(page.getCurPage());
		pageResponse.setRows(page.getRows());
		pageResponse.setSize(page.getSize());
		pageResponse.setStartRowNo(page.getStartRowNo());
		pageResponse.setTotalPage(page.getTotalPage());
		pageResponse.setObjectList(toResponse(page.getObjectList(), storageClient));
		return pageResponse;
	}
	
}
